import { log } from 'console';
import { onUnmounted, ref } from 'vue';

let ws: WebSocket | null = null;
const receivedData = ref<any[]>([]); // 初始化接收数据的ref

export default function useWebSocket(url: string, token: string) {
  // 创建WebSocket连接
  function initWebSocket() {
    const fullUrl = `${url}?token=${encodeURIComponent(token)}`;

    // if (ws) {
    //   ws.close();
    // }

    ws = new WebSocket(fullUrl);

    ws.addEventListener('open', () => {
      
    });

    ws.addEventListener('message', (event: MessageEvent<string>) => {
      const data = JSON.parse(event.data);
      receivedData.value.push(data);
      // 处理接收到的数据
      handleIncomingData(data);
    });

    ws.addEventListener('error', (err) => {
      console.error('WebSocket错误:', err);
    });

    ws.addEventListener('close', () => {
      ws = null;
      
    });
  }

  // 在组件卸载时关闭连接
  onUnmounted(closeWebSocket);

  function closeWebSocket() {
    if (ws) {
      ws.close();
    }
  }

  // 发送数据的函数
  function sendData(message: any) {
    log;
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify(message));
    } else {
      console.warn('WebSocket未连接，无法发送数据');
    }
  }

  // 初始化WebSocket连接
  initWebSocket();

  return {
    receivedData,
    sendData,
  };
}

// 示例处理数据函数
function handleIncomingData(data: any) {
  // 根据实际业务逻辑处理数据
}
